/*
 *   Copyright 2012-present OSBI Ltd
 *
 *   Licensed under the Apache License, Version 2.0 (the "License");
 *   you may not use this file except in compliance with the License.
 *   You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *   Unless required by applicable law or agreed to in writing, software
 *   distributed under the License is distributed on an "AS IS" BASIS,
 *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *   See the License for the specific language governing permissions and
 *   limitations under the License.
 */

// Packages
import React, { Component, Fragment } from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import { NavLink } from 'react-router-dom';
import {
  Icon,
  Menu,
  MenuDivider,
  MenuItem,
  Popover,
  Position,
  Tooltip
} from '@blueprintjs/core';

// Actions
import { actionCreators } from '../../../actions';

// UI
import Logo from '../../UI/Logo';
import ToolbarActions from './ToolbarActions';

// Dialogs
import {
  AboutDialog,
  EnterLicenseDialog,
  IssueReporterDialog,
  KeyboardShortcutsDialog
} from '../../Dialogs';

// Utils
import { Links, Saiku } from '../../../utils';

// Styles
import './Toolbar.css';
import './ToolbarActions.css';

class Toolbar extends Component {
  state = {
    isOpenAboutDialog: false,
    isOpenEnterLicenseDialog: false,
    isOpenKeyboardShortcutsDialog: false,
    isOpenIssueReporterDialog: false
  };

  toggleActionsBodyClass = () => {
    document.body.classList.toggle('toolbar-actions-open');
  };

  handleAboutDialog = () => {
    this.setState(prevState => ({
      isOpenAboutDialog: !prevState.isOpenAboutDialog
    }));
  };

  handleEnterLicenseDialog = () => {
    this.setState(prevState => ({
      isOpenEnterLicenseDialog: !prevState.isOpenEnterLicenseDialog
    }));
  };

  handleKeyboardShortcutsDialog = () => {
    this.setState(prevState => ({
      isOpenKeyboardShortcutsDialog: !prevState.isOpenKeyboardShortcutsDialog
    }));
  };

  handleIssueReporterDialog = () => {
    this.setState(prevState => ({
      isOpenIssueReporterDialog: !prevState.isOpenIssueReporterDialog
    }));
  };

  handleLogout = () => {
    this.props.doLogout(true);
  };

  render() {
    const { user } = this.props;
    const {
      isOpenAboutDialog,
      isOpenEnterLicenseDialog,
      isOpenKeyboardShortcutsDialog,
      isOpenIssueReporterDialog
    } = this.state;
    const { username, isadmin } = user;
    const isSaikuDemo = Saiku.isSaikuDemo();
    const profileMenu = (
      <Menu>
        <MenuDivider title={`${username}`} />
        <MenuDivider />
        <MenuItem
          icon="dollar"
          text="Purchase License"
          href={Links.saiku.license}
          target="_blank"
        />
        {isadmin && !isSaikuDemo && (
          <MenuItem
            icon="key"
            text="Enter License"
            onClick={this.handleEnterLicenseDialog}
          />
        )}
        <MenuItem icon="help" text="Help">
          <MenuDivider title="Help" />
          <MenuItem
            text="Documentation"
            href={Links.saiku.docs.home}
            target="_blank"
          />
          <MenuItem
            text="Tutorials"
            href={Links.saiku.docs.tutorials}
            target="_blank"
          />
          <MenuItem
            text="Keyboard Shortcuts"
            onClick={this.handleKeyboardShortcutsDialog}
          />
          <MenuItem
            text="Issue Reporter"
            onClick={this.handleIssueReporterDialog}
          />
          <MenuDivider title="Information" />
          <MenuItem
            text="Plans & Pricing"
            href={Links.meteorite.products.saiku.pricing}
            target="_blank"
          />
          <MenuItem text="Twitter" href={Links.saiku.twitter} target="_blank" />
          <MenuDivider />
          <MenuItem text="About" onClick={this.handleAboutDialog} />
        </MenuItem>
        {!isSaikuDemo && (
          <Fragment>
            <MenuDivider />
            <MenuItem icon="power" text="Log out" onClick={this.handleLogout} />
          </Fragment>
        )}
      </Menu>
    );

    return (
      <div className="sku-toolbar">
        <div className="sku-toolbar-inner">
          <div className="sku-logo">
            <Logo width={50} height={50} small />
          </div>
          <ul>
            <li>
              <Tooltip content={<span>Home</span>} position={Position.RIGHT}>
                <NavLink to="/home">
                  <Icon icon="home" title={false} />
                </NavLink>
              </Tooltip>
            </li>
            <li>
              <Tooltip
                content={<span>Create New</span>}
                position={Position.RIGHT}
              >
                <button
                  type="button"
                  className="link-button"
                  onClick={this.toggleActionsBodyClass}
                >
                  <Icon icon="plus" title={false} />
                </button>
              </Tooltip>
            </li>
            <li>
              <Tooltip
                content={<span>Query Manager</span>}
                position={Position.RIGHT}
              >
                <NavLink to="/settings/querymanager">
                  <Icon icon="folder-open" title={false} />
                </NavLink>
              </Tooltip>
            </li>
            {isadmin && !isSaikuDemo && (
              <li>
                <Tooltip
                  content={<span>Admin Console</span>}
                  position={Position.RIGHT}
                >
                  <NavLink to="/settings/adminconsole">
                    <Icon icon="console" title={false} />
                  </NavLink>
                </Tooltip>
              </li>
            )}
          </ul>
          <ul className="sku-toolbar-bottom">
            <li>
              <Tooltip
                content={<span>Settings</span>}
                position={Position.RIGHT}
              >
                <NavLink to="/settings/general">
                  <Icon icon="cog" title={false} />
                </NavLink>
              </Tooltip>
            </li>
            <li>
              <Popover
                content={profileMenu}
                position={Position.RIGHT_BOTTOM}
                autoFocus={false}
                enforceFocus={false}
              >
                <Tooltip
                  content={<span>Profile</span>}
                  position={Position.RIGHT}
                >
                  <button
                    type="button"
                    className="link-button"
                    onClick={e => e.preventDefault()}
                  >
                    <Icon icon="user" title={false} />
                  </button>
                </Tooltip>
              </Popover>
            </li>
          </ul>

          <ToolbarActions />

          {isOpenAboutDialog && (
            <AboutDialog onClose={this.handleAboutDialog} />
          )}

          {isOpenEnterLicenseDialog && (
            <EnterLicenseDialog
              toastPosition="TOP_RIGHT"
              onClose={this.handleEnterLicenseDialog}
            />
          )}

          {isOpenKeyboardShortcutsDialog && (
            <KeyboardShortcutsDialog
              onClose={this.handleKeyboardShortcutsDialog}
            />
          )}

          {isOpenIssueReporterDialog && (
            <IssueReporterDialog onClose={this.handleIssueReporterDialog} />
          )}
        </div>
      </div>
    );
  }
}

Toolbar.propTypes = {
  user: PropTypes.object.isRequired,
  doLogout: PropTypes.func.isRequired
};

const mapStateToProps = state => ({
  ...state.session
});

const mapDispatchToProps = dispatch => ({
  doLogout: forceLogout => dispatch(actionCreators.doLogout(forceLogout))
});

export default connect(
  mapStateToProps,
  mapDispatchToProps
)(Toolbar);
